package com.tom.angel.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tom.angel.dao.MenuDaoI;
import com.tom.angel.model.Menu;
import com.tom.angel.pagemodel.TreeMenuPageModel;
import com.tom.angel.service.MenuServiceI;

@Service("menuService")
public class MenuServiceImpl implements MenuServiceI {
	
	/**
	 * 自动注入MenuDaoImpl
	 */
	private MenuDaoI menuDao;

	public MenuDaoI getMenuDao() {
		return menuDao;
	}

	@Autowired
	public void setMenuDao(MenuDaoI menuDao) {
		this.menuDao = menuDao;
	}

	
	public List<TreeMenuPageModel> getMenu(Menu menu,boolean flag) {
		List<Object> params =new ArrayList<Object>();
		String hql = "from Menu m where m.menu = null";
		if (menu != null && menu.getId() != 0 ) {  
            params.add(menu.getId());
            hql = "from Menu m where m.menu.id = "+params.get(0);
        }
		List<Menu> menus = menuDao.find(hql);
		
		List<TreeMenuPageModel> treeList = new ArrayList<TreeMenuPageModel>();
		
		for (Menu m : menus) {
			treeList.add(getTreeNode(m,flag));
		}
		return treeList;
	}
	
	private TreeMenuPageModel getTreeNode(Menu m, boolean flag){
		TreeMenuPageModel treeMenu = new TreeMenuPageModel();
		treeMenu.setId(m.getId());
		treeMenu.setText(m.getText());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("url", m.getMenuUrl());
		treeMenu.setAttributes(attributes);
		/**
		 * 下面部分为，菜单图片设置
		 * if(m.getCiconcls() != null) {  
	     *      treeMenu.setIconCls(m.getCiconcls());  
	     *   	} else {  
	     *      treeMenu.setIconCls("");  
         * 	}  
		 */
		
		
		if(m.getMenus() != null && m.getMenus().size()>0){
			treeMenu.setState("closed");
			
			if(flag){
				List<Menu> menus = new ArrayList<Menu>();
				
				List<TreeMenuPageModel> children = new ArrayList<TreeMenuPageModel>();
				
				for (Menu t : menus) {
					TreeMenuPageModel treeMenuPageModel = getTreeNode(t,true);
					children.add(treeMenuPageModel);
				}
				treeMenu.setChildren(children);
			}
		}
		return treeMenu;
	}

	public Menu findMenu(int id) {
		Menu menu = new Menu();
		String hql = "from Menu m where m.id = "+id;
		List<Menu>menus = new ArrayList<Menu>();
		menus = menuDao.find(hql);
		menu = menus.get(0);
		return menu;
	}
}
